﻿// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;

    var resultsPane;

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll().then(function (e) {

                resultsPane = e.querySelector(".results");

                var list = e.querySelector(".tests").winControl;
                var bindingList = new WinJS.Binding.List([{ id: "fib", title: "Fibonacci Sin Promise" },
                    { id: "fibAsync", title: "Fibonacci en Web Worker" },
                    {id:"fibFakePromise",title: "Fibonacci en Promise (falsa)"},
                    { id: "fibAsyncPromise", title: "Fibonacci en Web Worker con Promise" },
                    {id:"webRequest",title:"petición web"},
                    { id: "imagePromise", title: "Promise con imagen" },
                     { id: "dataPromise", title: "Promise de datos" }]);
                list.itemDataSource = bindingList.dataSource;
            }));
        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };

    app.start();

    var worker = new Worker("/js/longrunningworker.js");

    function log(text) {
        if (resultsPane) {
           
            resultsPane.innerHTML += toStaticHTML(text) + "<br/>";
        }
        else
            console.log(text);
    }
    function clearLog() {
        if (resultsPane)
            resultsPane.innerHTML = "";
        else
            console.clear();
    }

    function startTest(e) {
        e.detail.itemPromise.then(function (x) {
            switch (x.data.id) {
                case "fib":
                    clearLog();
                    log("Calculando fib de 0 a 30");
                    for (var i = 0; i < 31; i++) {
                        log( "Fibonacci de " + i + ":" + LongRunning.fibonacci(i));
                    }
                    break;
                case "fibAsync":
                    clearLog();
                    log("Calculando fib de 0 a 30 Async");
                    worker.onmessage = function (e) {
                        log("Fibonacci de " + e.data.number + ":" + e.data.result);
                    };
                    worker.postMessage({ number: 30 });

                    break;
                case "fibFakePromise":
                    clearLog();
                    log("Calculando fib de 0 a 30 Async con promise");
                    fakeFibAsync(30).then(function (r) {
                        log("Fibonacci de " + r.number + ":" + r.result);
                    },
                    function (err) {
                        log("<b>Hubo un error:" + err + "</b>");
                    },
                    function progress(r) {
                        log("Fibonacci de " + r.number + ":" + r.result);
                    }
                    );
                    break;
                case "fibAsyncPromise":
                    clearLog();
                    log("Calculando fib de 0 a 30 Async con promise");
                        fibAsync(30).then(function (r) {
                            log("Fibonacci de " + r.number + ":" + r.result);
                        },
                        function (err) {
                            log("<b>Hubo un error:" + err + "</b>");
                        },
                        function progress(r) {
                            log("Fibonacci de " + r.number + ":" + r.result);
                        }
                        );
                        break;
                case "webRequest":
                    webRequest();
                    break;
                case "xhrPromise":
                    break;
            }
        });
    }

    function webRequest() {
        var url, xhr, results;
        clearLog();

        url = 'http://jmservera.com/feed/';
        xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        log("url abierta");
        //evento de carga
        xhr.onload = function (e) {
            if (this.status === 200) {
                log("respuesta: "+this.responseText);
            }
        };

        //evento de error
        xhr.onerror = function (e) {
            log("error: "+e);
        };

        //aquí empieza la llamada asíncrona
        xhr.send();
        log("Petición enviada");

    }

    function fibAsync(n) {
        return new WinJS.Promise(function (success, error, progress) {
            try {
                var f = function (e) {
                    if (e.data.number == n) {
                        success(e.data);
                        worker.removeEventListener("message", f, false);
                    }
                    else {
                        progress(e.data);
                    }
                };
                worker.addEventListener("message", f, false);
                worker.postMessage({ number: n });
            } catch (ex) {
                error(ex);
            }
        });
    }

    function fakeFibAsync(n) {
        return new WinJS.Promise(function (success, error, progress) {
            try {
                for (var i = 0; i < n; i++) {
                    progress({ number: i, result: LongRunning.fibonacci(i) });
                }
                success({ number: n, result: LongRunning.fibonacci(n) });
            } catch (ex) {
                error(ex);
            }
        });
    }

    WinJS.Utilities.markSupportedForProcessing(startTest);

    WinJS.Namespace.define("Demos", {
        startTest:startTest
    });
})();
